package egovframework.npqs.pqi.mobile.activity.quarantinerequest;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import egovframework.npqs.pqi.mobile.AppStatus;
import egovframework.npqs.pqi.mobile.R;
import egovframework.npqs.pqi.mobile.activity.ProdDetailActivity;
import egovframework.npqs.pqi.mobile.activity.disinfection.DisinfectionDetailActivity;
import egovframework.npqs.pqi.mobile.activity.exportquarantineresult.ExportQuarantineResultDetail;
import egovframework.npqs.pqi.mobile.activity.quarantineresult.QuarantineResultDetail;
import egovframework.npqs.pqi.mobile.jsoncontent.ErrorItem;
import egovframework.npqs.pqi.mobile.jsoncontent.QuarantineRequestDetailItem;
import egovframework.npqs.pqi.mobile.jsoncontent.listitem.ProdItem;
import egovframework.npqs.pqi.mobile.jsoncontent.listitem.QunCdItem;
import egovframework.npqs.pqi.mobile.jsonparser.QuarantineRequestDetailThread;
import egovframework.npqs.pqi.mobile.jsonparser.QuarantineRequestDetailThread.QuarantineRequestDetailThreadCallback;
import egovframework.npqs.pqi.mobile.jsonparser.QuarantineRequestUpdateThread;
import egovframework.npqs.pqi.mobile.jsonparser.QuarantineRequestUpdateThread.QuarantineRequestUpdateThreadCallback;

//검역신청상세조회
public class QuarantineRequestDetailActivity extends Activity implements 
	QuarantineRequestDetailThreadCallback, OnClickListener
	, QuarantineRequestUpdateThreadCallback{
	private TextView titleTxt;	// 상단 타이틀
	private AppStatus myapp;
	private Context context;
	
	private String recNo, success, rceptDate, rceptDateHh, rceptDateMi, viewRecNamCdAcnt, viewRecNamCdNm;	// 검역신청 상세번호, , 접수일시 날짜, 접수일시 시간, 접수일시 분
	private String venRnAdres, venRnAdresDetail;	// 수출입자:도로명주소, 수출입자:도로명상세주소
	private EditText offCdEdit, requestNumEdit, edit_request_num;	// 검역신청검역지 코드 에디트 박스, 검역신청 상세번호 에디트 박스
	private Button footerBtn01, footerBtn02, footerBtn03, footerBtn04;	// 하단 버튼
	
	private TextView headerTotTxt, navigation;
	private TextView validflagNm, trnNm, traDe, terDe;	//검역구분명, 수출입구분, 입항일자, 처리기한
	private TextView qrantHde, fullRceptDate, fullViewRecNamCd, insPlace;	//검역희망일시, 접수일시, 민원담당자, 검역장소
	private TextView obiwuTrgetAt, viewReqstProgrsSt, delayCheck, metNm;	//선상검역대상여부, 진행상태, 지연신고, 운송형태
	private TextView loadNm, loadSp, arivSp, natNm; //선기명, 선적항, 국내도착항, 수입국
	private TextView orgNatNm, orgAreNm, pasNatNm, caseCd;	//원산지, 지역, 경유지, 포장종류
	private TextView totQty, caseSt, expNm, hwaNo;	//총포장개수, 포장재상태, 수입용도, 화물관리번호
	private TextView cvodv, blNo, venNm, venRep;	//과세가격, bl번호, 수출입자:업체명, 수출입자:대표자
	private TextView venResNo, venComlice, venTelNo, venCelphn;	//수출입자:생년월일, 수출입자:사업자번호, 수출입자:전화번호, 수출입자:휴대번호
	private TextView venSmsChk, fullRnAdres, ven2Nm, ven2RepNm;	//수출입자:SMS희망, 수출입자:풀주소, 송수하인:업체명, 송수하인:성명
	private TextView ven2Adres, agentNm, agentCelphn, agentSmsChk;	//송수하인:주소, 신청인:업체명, 신청인:휴대전화, 신청인:SMS희망
	private TextView agentTelNo, agentFaxno, agentEmail, agentReq;	//신청인:연락처, 신청인:팩스번호, 신청인:이메일, 신청인:요구사항
	
	private ImageButton upBtn, downBtn, searchBtn, btnHome, btn_back;
	
	private ListView listView;
	private QuarantineDetailListAdapter quarantineDetailListAdapter;
	private ArrayList<ProdItem> prodArrList;
	private ArrayList<QunCdItem> quncdArrList;
	private ArrayList<String> spinArrList;
	
	private QuarantineRequestUpdateThread quarantineUpdateThread;
	private QuarantineRequestDetailThread quarantineDetailThread;
	private QuarantineRequestDetailItem quarantineDetailItem;
	
	private final static int MSG_QUARANTINE_COMPLETED = 0;
	private final static int MSG_QUARANTINE_ERROR = 1;
	private final static int MSG_NETWORK_ERROR = 2;
	private final static int MSG_QUARANTINE_UPDATE_COMPLETED = 3;
	private final static int MSG_QUARANTINE_UPDATE_ERROR = 4;
	
	//하단 리스트 해더
	private LinearLayout list_header_Layout;
	private String trnCd, ingState;
	private boolean searchState;
	
	//하단 품목 컴포넌트
	TextView txt_seq, txt_trfclsf_cd, detail_list_hs_cd, text_hs_code;
	TextView txt_prod_name, txt_qun_cd;
	Spinner spn_qun_cd;
	EditText edit_itm_qty;
	ImageButton search_cd_btn; 
	
	private int posit;
	private String mResult;
	
	/* G-MOBILE 변수*/
    private String temp;
    private String requestNum;
    HashMap<String, String> map;
    JSONObject resultData;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		AppStatus.navigation.addPathLocation("검역신청상세조회");
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_request_detail);
		Intent intent = getIntent();
		recNo = intent.getStringExtra("recNo");
		trnCd = "";
		init();
		
	}
	
	private void init(){
		context = this;
		myapp = (AppStatus) getApplicationContext();
		myapp.startBroker(context);
		
		titleTxt = (TextView)findViewById(R.id.headerTitleText);
		titleTxt.setText("검역신청상세조회");
		
		navigation = (TextView)findViewById(R.id.navigation);
		navigation.setText(AppStatus.navigation.getPath());
		Log.i("AppStatus.navigation.getPath()->", AppStatus.navigation.getPath());
		System.out.println("eifj :: "+AppStatus.navigation.toString());
		
		//하단 리스트 해더
		list_header_Layout = (LinearLayout)findViewById(R.id.list_header_Layout);
		
		offCdEdit = (EditText)findViewById(R.id.edit_offcd);
		offCdEdit.setText(myapp.getLoginItem().getOffCd());
		
		requestNumEdit = (EditText)findViewById(R.id.edit_request_num);
		requestNumEdit.setText(recNo);
		
		searchBtn = (ImageButton)findViewById(R.id.search_btn);
		searchBtn.setOnClickListener(this);
		
		/*loginBtn = (ImageButton)findViewById(R.id.btnLogin);
		loginBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				myapp.appFinish(QuarantineRequestDetailActivity.this);				
			}
		});*/
		
		btn_back = (ImageButton)findViewById(R.id.btn_back);
		btn_back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				onBackPressed();
			}
		});
		
		btnHome = (ImageButton)findViewById(R.id.btnHome);
		btnHome.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				myapp.setAbleHome(true);
				finish();
			}
		});
		
		searchState = false;
		
		listView = (ListView)findViewById(R.id.quarantine_detail_list);
		quarantineDetailListAdapter = new QuarantineDetailListAdapter();
		
		validflagNm = (TextView)findViewById(R.id.validflagNm);
		trnNm = (TextView)findViewById(R.id.trnNm);
		traDe = (TextView)findViewById(R.id.traDe);
		terDe = (TextView)findViewById(R.id.terDe);
		qrantHde = (TextView)findViewById(R.id.qrantHde);
		fullRceptDate = (TextView)findViewById(R.id.fullRceptDate);
		fullViewRecNamCd = (TextView)findViewById(R.id.fullViewRecNamCd);
		insPlace = (TextView)findViewById(R.id.insPlace);
		obiwuTrgetAt = (TextView)findViewById(R.id.obiwuTrgetAt);
		viewReqstProgrsSt = (TextView)findViewById(R.id.viewReqstProgrsSt);
		delayCheck = (TextView)findViewById(R.id.delayCheck);
		metNm = (TextView)findViewById(R.id.metNm);
		loadNm = (TextView)findViewById(R.id.loadNm);
		loadSp = (TextView)findViewById(R.id.loadSp);
		arivSp = (TextView)findViewById(R.id.arivSp);
		natNm = (TextView)findViewById(R.id.natNm);
		orgNatNm = (TextView)findViewById(R.id.orgNatNm);
		orgAreNm = (TextView)findViewById(R.id.orgAreNm);
		pasNatNm = (TextView)findViewById(R.id.pasNatNm);
		caseCd = (TextView)findViewById(R.id.caseCd);
		totQty = (TextView)findViewById(R.id.totQty);
		caseSt = (TextView)findViewById(R.id.caseSt);
		expNm = (TextView)findViewById(R.id.expNm);
		hwaNo = (TextView)findViewById(R.id.hwaNo); //화물관리번호
		cvodv = (TextView)findViewById(R.id.cvodv);
		blNo = (TextView)findViewById(R.id.blNo); //bl번호
		venNm = (TextView)findViewById(R.id.venNm);
		venRep = (TextView)findViewById(R.id.venRep);
		venResNo = (TextView)findViewById(R.id.venResNo);
		venComlice = (TextView)findViewById(R.id.venComlice);
		venTelNo = (TextView)findViewById(R.id.venTelNo);
		venCelphn = (TextView)findViewById(R.id.venCelphn);
		venSmsChk = (TextView)findViewById(R.id.venSmsChk);
		fullRnAdres = (TextView)findViewById(R.id.fullRnAdres);
		ven2Nm = (TextView)findViewById(R.id.ven2Nm);
		ven2RepNm = (TextView)findViewById(R.id.ven2RepNm);
		ven2Adres = (TextView)findViewById(R.id.ven2Adres);
		agentNm = (TextView)findViewById(R.id.agentNm);
		agentCelphn = (TextView)findViewById(R.id.agentCelphn);
		agentSmsChk = (TextView)findViewById(R.id.agentSmsChk);
		agentTelNo = (TextView)findViewById(R.id.agentTelNo);
		agentFaxno = (TextView)findViewById(R.id.agentFaxno);
		agentEmail = (TextView)findViewById(R.id.agentEmail);
		agentReq = (TextView)findViewById(R.id.agentReq);
		text_hs_code = (TextView)findViewById(R.id.text_hs_code);
		
		//전화번호 링크걸기 + 누르면 전화하기 
		venTelNo.setPaintFlags(venTelNo.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
		venTelNo.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Uri n = Uri.parse("tel: "+venTelNo.getText());
				startActivity(new Intent(Intent.ACTION_DIAL, n));
			}
		});
		
		//휴대폰 링크걸기 + 누르면 전화하기
		venCelphn.setPaintFlags(venCelphn.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
		venCelphn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Uri n = Uri.parse("tel: "+venCelphn.getText());
				startActivity(new Intent(Intent.ACTION_DIAL, n));
			}
		});
		//신청인 연락처 링크걸기 + 전화하기
		agentTelNo.setPaintFlags(agentTelNo.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
		agentTelNo.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Uri n = Uri.parse("tel: "+agentTelNo.getText());
				startActivity(new Intent(Intent.ACTION_DIAL, n));
			}
		});
		
		edit_request_num = (EditText)findViewById(R.id.edit_request_num);
		
		footerBtn01 = (Button)findViewById(R.id.footer01Btn);
		footerBtn02 = (Button)findViewById(R.id.footer02Btn);
		footerBtn03 = (Button)findViewById(R.id.footer03Btn);
		footerBtn04 = (Button)findViewById(R.id.footer04Btn);
		
		//footerBtn01.setOnClickListener(this);
		footerBtn02.setOnClickListener(this);
		footerBtn03.setOnClickListener(this);
		//footerBtn04.setOnClickListener(this);
		footerBtn01.setBackgroundResource(R.drawable.f_blank_sel);
		footerBtn04.setBackgroundResource(R.drawable.f_blank_sel);
		
		myapp.showDialogNo(context);
		temp = "처음검색";
		//asyncTaskIsConnectedVPN();
		threadStart();
		
	}
	
	private void searchDetail(String requestNum){
		searchState = true;
		this.requestNum = requestNum;
		myapp.showDialogNo(context);	// 페이지가 로드 될때 다이얼로그 출력.
		temp = "조건검색";
		//asyncTaskIsConnectedVPN();
		threadStart();
	}
	
	public void threadStart(){
		if("조건검색".equals(temp)){
			myapp.utilm.InputKeybordHidden(context, requestNumEdit);
    		quarantineDetailThread = new QuarantineRequestDetailThread(context
    				, this, myapp.getLoginItem().getOffCd(), requestNum, AppStatus.getmUserId());
    		quarantineDetailThread.start();
    	}
    	if("처음검색".equals(temp)){
    		quarantineDetailThread = new QuarantineRequestDetailThread(context
    				, this, myapp.getLoginItem().getOffCd(), recNo, AppStatus.getmUserId());
    		quarantineDetailThread.start();
    	}
    	if("저장".equals(temp)){
    		quarantineUpdateThread = new QuarantineRequestUpdateThread(context, this
    				, resultData.toString(), AppStatus.getmUserId());
    		quarantineUpdateThread.start();
    	}
  	}
	
	private void layoutSetting(){
		trnCd = quarantineDetailItem.getTrnCd();
		ingState = quarantineDetailItem.getViewReqstProgrsSt();
		validflagNm.setText(quarantineDetailItem.getValidflagNm());
		trnNm.setText(quarantineDetailItem.getTrnNm());
		traDe.setText(quarantineDetailItem.getTraDe());
		terDe.setText(quarantineDetailItem.getTerDe());
		qrantHde.setText(quarantineDetailItem.getQrantHde());
		rceptDate = quarantineDetailItem.getRceptDate();
		rceptDateHh = quarantineDetailItem.getRceptDateHh();
		rceptDateMi = quarantineDetailItem.getRceptDateMi();
		fullRceptDate.setText(rceptDate +" "+ rceptDateHh +":"+ rceptDateMi);
		viewRecNamCdAcnt = quarantineDetailItem.getViewRecNamCdAcnt();
		viewRecNamCdNm = quarantineDetailItem.getViewRecNamCdNm();
		fullViewRecNamCd.setText(viewRecNamCdAcnt +" " + viewRecNamCdNm);
		insPlace.setText(quarantineDetailItem.getInsPlace());
		obiwuTrgetAt.setText(quarantineDetailItem.getObiwuTrgetAt());
		viewReqstProgrsSt.setText(quarantineDetailItem.getViewReqstProgrsSt());
		delayCheck.setText(quarantineDetailItem.getDelayCheck());
		metNm.setText(quarantineDetailItem.getMetNm());
		loadNm.setText(quarantineDetailItem.getLoadNm());
		loadSp.setText(quarantineDetailItem.getLoadSp());
		arivSp.setText(quarantineDetailItem.getArivSp());
		natNm.setText(quarantineDetailItem.getNatNm());
		orgNatNm.setText(quarantineDetailItem.getOrgNatNm());
		orgAreNm.setText(quarantineDetailItem.getOrgAreNm());
		pasNatNm.setText(quarantineDetailItem.getPasNatNm());
		caseCd.setText(quarantineDetailItem.getCaseCd());
		totQty.setText(quarantineDetailItem.getTotQty());
		caseSt.setText(quarantineDetailItem.getCaseSt());
		expNm.setText(quarantineDetailItem.getExpNm());
		hwaNo.setText(quarantineDetailItem.getHwaNo());
		cvodv.setText(quarantineDetailItem.getCvodv());
		blNo.setText(quarantineDetailItem.getBlNo());
		venNm.setText(quarantineDetailItem.getVenNm());
		venRep.setText(quarantineDetailItem.getVenRep());
		venResNo.setText(quarantineDetailItem.getVenResNo());
		venComlice.setText(quarantineDetailItem.getVenComlice());
		venTelNo.setText(quarantineDetailItem.getVenTelNo());
		venCelphn.setText(quarantineDetailItem.getVenCelphn());
		venSmsChk.setText(quarantineDetailItem.getVenSmsChk());
		venRnAdres = quarantineDetailItem.getVenRnAdres();
		venRnAdresDetail = quarantineDetailItem.getVenRnAdresDetail();
		fullRnAdres.setText(venRnAdres + " " + venRnAdresDetail);
		ven2Nm.setText(quarantineDetailItem.getVen2Nm());
		ven2RepNm.setText(quarantineDetailItem.getVen2RepNm());
		ven2Adres.setText(quarantineDetailItem.getVen2Adres());
		agentNm.setText(quarantineDetailItem.getAgentNm());
		agentCelphn.setText(quarantineDetailItem.getAgentCelphn());
		agentSmsChk.setText(quarantineDetailItem.getAgentSmsChk());
		agentTelNo.setText(quarantineDetailItem.getAgentTelNo());
		agentFaxno.setText(quarantineDetailItem.getAgentFaxno());
		agentEmail.setText(quarantineDetailItem.getAgentEmail());
		agentReq.setText(quarantineDetailItem.getAgentReq());
		
		prodArrList = quarantineDetailItem.getItems();
		
		quncdArrList = quarantineDetailItem.getQunCdList();
		if(quncdArrList.size() > 0){
			spinArrList = new ArrayList<String>();
			for (int i = 0; i < quncdArrList.size(); i++) {
				spinArrList.add(quncdArrList.get(i).getCodeNm());
			}
		}
		
		list_header_Layout.setVisibility(View.VISIBLE);
		
		listView.setVisibility(View.VISIBLE);
		
		headerTotTxt = (TextView)findViewById(R.id.header_tot);
		upBtn = (ImageButton)findViewById(R.id.header_up_btn);
		downBtn = (ImageButton)findViewById(R.id.header_down_btn);

		headerTotTxt.setText("총 품목:"+quarantineDetailItem.getItemsResult()+"건");
		listView.setAdapter(quarantineDetailListAdapter);
		
		upBtn.setOnClickListener(this);
		downBtn.setOnClickListener(this);
		
		downBtn.performClick();
	}
	
	/*private void requestSave(){
		//JSONObject resultData = new JSONObject();
		String resultData = "";
		JSONArray requestArray = new JSONArray();
		JSONObject obj;
		
		for (int i = 0; i < prodArrList.size(); i++) {
			 View v = quarantineDetailListAdapter.getView(i, null, listView);
			EditText editText=(EditText) v.findViewById(R.id.detail_list_itm_qty);
		       
			try {
				obj = new JSONObject();
				obj.put("offCd", prodArrList.get(i).getOffCd());
				obj.put("recNo", prodArrList.get(i).getRecNo());
				obj.put("recSeq", prodArrList.get(i).getRecSeq());
				obj.put("itmQty", editText.getText().toString());
				obj.put("qunCd", prodArrList.get(i).getQunCd());
				obj.put("updNamCd", myapp.getLoginItem().getUserSn());
				
				obj.put("prdlstCode", prodArrList.get(i).getPrdlstCode());
				obj.put("prdlstNm", prodArrList.get(i).getPrdlstNm());
				obj.put("hsCd", prodArrList.get(i).getHsCd());
				
				requestArray.put(obj);
				//resultData += "{resultData:"+requestArray.toString()+"}";
				resultData += requestArray.toString();
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		HashMap<String, String> rmap = new HashMap<String, String>();
		rmap.put("resultData", resultData);
		String returntData = rmap.toString();
		
		map = new HashMap<String, String>();
		map.put("resultData", returntData);
		
		showDialogNo();
		temp = "저장";
		threadStart();
	}*/
	
	private void requestSave2(){
		resultData = new JSONObject();
		JSONArray requestArray = new JSONArray();
		JSONObject obj;
		for (int i = 0; i < prodArrList.size(); i++) {
			View v = quarantineDetailListAdapter.getView(i, null, listView);
			EditText editText=(EditText) v.findViewById(R.id.detail_list_itm_qty);
			try {
				obj = new JSONObject();
				obj.put("offCd", prodArrList.get(i).getOffCd());
				obj.put("recNo", prodArrList.get(i).getRecNo());
				obj.put("recSeq", prodArrList.get(i).getRecSeq());
				obj.put("itmQty", editText.getText().toString());
				obj.put("qunCd", prodArrList.get(i).getQunCd());
				obj.put("updNamCd", myapp.getLoginItem().getUserSn());
				
				obj.put("prdlstCode", prodArrList.get(i).getPrdlstCode());
				obj.put("prdlstNm", prodArrList.get(i).getPrdlstNm());
				obj.put("hsCd", prodArrList.get(i).getHsCd());
				
				requestArray.put(obj);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		try {
			resultData.put("resultData", requestArray);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		myapp.showDialogNo(context);;
		temp = "저장";
		threadStart();
		
	}

	@Override
	public void OnQuarantineRequestDetailCompleted(boolean isNetworkConntected,
			QuarantineRequestDetailItem quarantineItem, String message) {
		Log.i("message-->", "message-->"+message);
		if(null != message && !"".equals(message)){
			mResult = message;
			reesultToast();
		}
		
		if(myapp.dialog !=null && myapp.dialog.isShowing()) {
			myapp.dialog.dismiss();
		}
		
		if(!isNetworkConntected){	// 네트워크 접속이 되어 있지 않을 때
			Message msg = handler.obtainMessage();
			msg.what = MSG_NETWORK_ERROR;
			handler.sendMessage(msg);
			return;
		}
		
		if(quarantineItem != null) {
			this.quarantineDetailItem = quarantineItem;
			Message msg = handler.obtainMessage();
			msg.what = MSG_QUARANTINE_COMPLETED;
			handler.sendMessage(msg);
		}	
	}

	@Override
	public void OnQuarantineRequestDetailError(ErrorItem errorItem) {
		if(myapp.dialog !=null && myapp.dialog.isShowing()) {
			myapp.dialog.dismiss();
		}

		Message msg = handler.obtainMessage();
		msg.what = MSG_QUARANTINE_ERROR;
		if(errorItem != null) {
			msg.obj = errorItem.getrDesc();
		}
		handler.sendMessage(msg);		
	}
	
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(final Message msg) {
			switch (msg.what) {
			case MSG_QUARANTINE_COMPLETED:
				layoutSetting();
				break;

			case MSG_QUARANTINE_ERROR:
				String errMsg = "";
				if(msg == null ||msg.obj.toString().equals("")){
					errMsg = "서버와의 연결에 실패하였습니다.";
				}else{
					errMsg = msg.obj.toString();	
				}
				listView.setVisibility(View.GONE);
				myapp.utilm.ShowDialog(QuarantineRequestDetailActivity.this, "실패", errMsg, 20);
				break;

			case MSG_NETWORK_ERROR:
				myapp.utilm.ShowDialog(QuarantineRequestDetailActivity.this, "실패", "네트워크에러", 20);
				break;

			case MSG_QUARANTINE_UPDATE_COMPLETED:
				new AlertDialog.Builder(QuarantineRequestDetailActivity.this)
				.setTitle("저장")
				.setMessage(success)
				.setPositiveButton("확인", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						try {
							searchDetail(prodArrList.get(0).getRecNo());
						} catch (Exception e) {

						}
					}
				})
				.setCancelable(false)
				.show();
				break;
				
			case MSG_QUARANTINE_UPDATE_ERROR:
				String errMsg1 = "";
				if(msg == null ||msg.obj.toString().equals("")){
					errMsg = "서버와의 연결에 실패하였습니다.";
				}else{
					errMsg = msg.obj.toString();	
				}
				myapp.utilm.ShowDialog(QuarantineRequestDetailActivity.this, "실패", errMsg1, 20);
				break;
				
			default:
				break;
			}
		}
	};
	
	class QuarantineDetailListAdapter extends BaseAdapter {
		@Override
		public int getCount() {
			return prodArrList.size();
		}

		@Override
		public Object getItem(int position) {
			return prodArrList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			if (convertView == null || convertView != null) {
    			LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    			convertView = inflater.inflate(R.layout.list_detail_item2, parent, false);
    		}
			txt_seq = (TextView)convertView.findViewById(R.id.detail_list_seq);
			txt_trfclsf_cd = (TextView)convertView.findViewById(R.id.detail_list_trfclsf_cd);
			txt_prod_name = (TextView)convertView.findViewById(R.id.detail_list_prod_name);
			spn_qun_cd = (Spinner)convertView.findViewById(R.id.detail_list_qun_cd);
			edit_itm_qty = (EditText)convertView.findViewById(R.id.detail_list_itm_qty);
			detail_list_hs_cd = (TextView)convertView.findViewById(R.id.detail_list_hs_cd);
			text_hs_code = (TextView)convertView.findViewById(R.id.text_hs_code);
			search_cd_btn = (ImageButton)convertView.findViewById(R.id.search_cd_btn);
			search_cd_btn.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(QuarantineRequestDetailActivity.this, ProdDetailActivity.class);
					intent.putExtra("prodCd", "no");
					posit = position;
					startActivityForResult(intent, 1);
				}
			});
			
			if(trnCd.equals("173003")||trnCd.equals("173004")){// 수입이면 보이게
				search_cd_btn.setVisibility(View.VISIBLE);
				text_hs_code.setVisibility(View.VISIBLE);
			}
			
			txt_seq.setText(prodArrList.get(position).getRecSeq());//순번
			txt_trfclsf_cd.setText(prodArrList.get(position).getPrdlstCode());//품목코드
			txt_prod_name.setText(prodArrList.get(position).getPrdlstNm());//품목명한영구분
			edit_itm_qty.setText(prodArrList.get(position).getItmQty());//수출입수량
			detail_list_hs_cd.setText(prodArrList.get(position).getHsCd());//hs코드
			spn_qun_cd.setPrompt("수량을 선택하세요.");
			
			ArrayAdapter<String> categoriesAdapter = new ArrayAdapter<String>(context, R.layout.spinner_item, spinArrList);
			//스피너 목록 검정색 으로 칠하기
			//categoriesAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			spn_qun_cd.setAdapter(categoriesAdapter);
			
			for (int i = 0; i < quncdArrList.size(); i++) {
				if(quncdArrList.get(i).getCode().equals(prodArrList.get(position).getQunCd())){
					spn_qun_cd.setSelection(i);
				}
			}
			
			spn_qun_cd.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

				@Override
				public void onItemSelected(AdapterView<?> parent, View view,
						int count, long id) {
					prodArrList.get(position).setQunCd(quncdArrList.get(count).getCode());
				}

				@Override
				public void onNothingSelected(AdapterView<?> parent) {
				}
			});
			
			edit_itm_qty.addTextChangedListener(new TextWatcher() {
				@Override
				public void onTextChanged(CharSequence s, int start, int before, int count) {}
				@Override
				public void beforeTextChanged(CharSequence s, int start, int count,int after) {}
				@Override
				public void afterTextChanged(Editable s) {
					prodArrList.get(position).setItmQty(s.toString());
				}
			});
			convertView.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					listItemClickEvent(position);
				}
			});
			
			return convertView;
		}
		
		private void listItemClickEvent(final int position) {
		}
	}	
	
	//온클릭
	@Override
	public void onClick(View v) {
		Intent intent ;
		switch (v.getId()) {
		
		case R.id.search_btn:
			if(edit_request_num.getText().toString().length()==8){
				searchDetail(requestNumEdit.getText().toString());
			}else{
				myapp.utilm.ShowDialog(QuarantineRequestDetailActivity.this, "실패", "검역신청 번호 뒤 8자리를 입력해 주세요.", 20);
			}
			break;
		
		case R.id.footer01Btn:	// 목록 버튼
			onBackPressed();
			break;
			
		case R.id.footer02Btn:	// 저장 버튼
			requestSave2();
			break;
			
		case R.id.footer03Btn:	// 검역결과등록 버튼
			//수입(trnCd) : 173003, 173004
			if(trnCd.equals("173003")||trnCd.equals("173004")){
				intent = new Intent(QuarantineRequestDetailActivity.this, QuarantineResultDetail.class);
				intent.putExtra("recNo", quarantineDetailItem.getRecNo());
				startActivity(intent);
			}
			//수출(trnCd) : 173001, 173002
			if(trnCd.equals("173001")||trnCd.equals("173002")){
				intent = new Intent(QuarantineRequestDetailActivity.this, ExportQuarantineResultDetail.class);
				intent.putExtra("recNo", quarantineDetailItem.getRecNo());
				startActivity(intent);
			}
			break;
			
		case R.id.footer04Btn:	// 소독결과등록 버튼
			if(trnCd.equals("173001")||trnCd.equals("173002")){
				myapp.utilm.ShowDialog(QuarantineRequestDetailActivity.this, "실패", "수출검역은 소독결과등록이 불가능합니다.", 20);
			}else if(ingState.equals("접수완료")){
				myapp.utilm.ShowDialog(QuarantineRequestDetailActivity.this, "실패", "검역결과번호가 등록되지 않은 검역신청서는 소독결과등록이 불가능합니다.", 20);
			}else{
				intent = new Intent(QuarantineRequestDetailActivity.this, DisinfectionDetailActivity.class);
				intent.putExtra("recNo", quarantineDetailItem.getOffCd()+"-"+quarantineDetailItem.getRecNo());
				intent.putExtra("value", "1");
				startActivity(intent);	
			}
			break;
			
		case R.id.header_up_btn:
			RelativeLayout.LayoutParams listParams = new RelativeLayout.LayoutParams
		    (LayoutParams.WRAP_CONTENT, myapp.utilm.getDpToPixel(context, 400));
			listParams.addRule(RelativeLayout.ABOVE, R.id.bottom_layout);
			listView.setLayoutParams(listParams);
			break;
			
		case R.id.header_down_btn:
			RelativeLayout.LayoutParams listParams1 = new RelativeLayout.LayoutParams
		    (LayoutParams.WRAP_CONTENT, myapp.utilm.getDpToPixel(context, 85));
			listParams1.addRule(RelativeLayout.ABOVE, R.id.bottom_layout);
			listView.setLayoutParams(listParams1);
			break;		

		default:
			break;
		}
	}

	@Override
	public void OnQuarantineRequestUpdateCompleted(boolean isNetworkConntected,
			String result, String message) {
		
		Log.i("message-->", "message-->"+message);
		if(null != message && !"".equals(message)){
			mResult = message;
			reesultToast();
		}
		
		if(myapp.dialog !=null && myapp.dialog.isShowing()) {
			myapp.dialog.dismiss();
		}
		
		if(!isNetworkConntected){	// 네트워크 접속이 되어 있지 않을 때
			Message msg = handler.obtainMessage();
			msg.what = MSG_NETWORK_ERROR;
			handler.sendMessage(msg);
			return;
		}
		
		if(!result.equals("")) {
			this.success = result;
			//저장이완료되면 리로딩이 되어야 한다.
			//myapp.setDataDetailLoadState(true);
			
			Message msg = handler.obtainMessage();
			msg.what = MSG_QUARANTINE_UPDATE_COMPLETED;
			handler.sendMessage(msg);
		}
		
	}

	@Override
	public void OnQuarantineRequestUpdatelError(ErrorItem errorItem) {
		if(myapp.dialog !=null && myapp.dialog.isShowing()) {
			myapp.dialog.dismiss();
		}

		Message msg = handler.obtainMessage();
		msg.what = MSG_QUARANTINE_UPDATE_ERROR;
		if(errorItem != null) {
			msg.obj = errorItem.getrDesc();
		}
		handler.sendMessage(msg);
	}
	
	@Override
	protected void onResume() {
		if(myapp.isFinishState()||myapp.isAbleHome()){
			finish();
		}
		if(myapp.isDataLoadState()){
			myapp.startBroker(context);
			myapp.setDataLoadState(false);
		}
		super.onResume();
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		//품목검색
		case 1:
			if(resultCode == 1){
				prodArrList.get(posit).setTrfclsfCode(data.getStringExtra("prdlstCode"));
				prodArrList.get(posit).setPrdlstNm(data.getStringExtra("prdlstNm"));
				prodArrList.get(posit).setHsCd(data.getStringExtra("hsCd"));
				layoutSetting();
			}else{
				Log.i("resultCode","resultCode  0 아님");
			}
			break;
			
		default:
			break;
		}
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		Log.i("onDestroy()", "onDestroy()");
		AppStatus.navigation.delPathLocation();
	}
	
	@Override
	protected void onStop() {
		super.onStop();
		Log.i("onStop()", "onStop()");
	}
	
	@Override
	protected void onRestart() {
		super.onRestart();
		Log.i("onRestart()", "onRestart()");
	}

	private void reesultToast() {
		runOnUiThread(new Runnable() {

            public void run() {
                Toast toast = Toast.makeText(context, mResult, Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 50);
                toast.show();
            }
        });
    }
	
}
